package com.zbkj.admin.controller.merchant;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.zbkj.common.model.express.Express;
import com.zbkj.common.model.express.MerchantExpress;
import com.zbkj.common.request.kdn.ElectronicAddService;
import com.zbkj.common.request.kdn.ElectronicCommodity;
import com.zbkj.common.request.kdn.ElectronicParam;
import com.zbkj.common.request.kdn.KdUtil;
import com.zbkj.service.service.ExpressService;
import com.zbkj.service.service.MerchantExpressService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/api/admin/merchant/electronicOrder")
@RequiredArgsConstructor
@Slf4j
public class KdApiElectronicOrder {

    @Value("${kd.EBusinessID}")
    private String EBusinessID;
    @Value("${kd.ApiKey}")
    private String ApiKey;

    @Autowired
    private MerchantExpressService expressService;

    //请求url, 正式环境地址
    private String ReqURL="https://api.kdniao.com/api/EOrderService";

    //电子面单接口
    @PostMapping("/orderOnlineByJson")
    public R<Object> orderOnlineByJson(@Validated @RequestBody ElectronicParam electronicParam) throws Exception{
        JSONObject json = new JSONObject();
        json.put("OrderCode", electronicParam.getOrderCode());
        json.put("ThrOrderCode", electronicParam.getThrOrderCode());
        //查询快递配置信息
        MerchantExpress express = expressService.getById(electronicParam.getExpressId());
        if (Objects.nonNull(express)){
            json.put("ShipperCode", express.getCode());
            json.put("CustomerName", express.getAccount());
            json.put("CustomerPwd", express.getPassword());
            json.put("MonthCode", express.getMonthCode());
            json.put("SendSite", express.getSendSite());
            json.put("SendStaff", express.getSendStaff());
        }
        json.put("PayType", electronicParam.getPayType());
        json.put("ExpType", electronicParam.getExpType());  //默认1
        json.put("Cost", electronicParam.getCost());
        json.put("OtherCost", electronicParam.getOtherCost());
        json.put("Weight", electronicParam.getWeight());
        json.put("Volume", electronicParam.getVolume());
        json.put("Quantity", electronicParam.getQuantity());
        json.put("IsNotice", electronicParam.getIsNotice());
        json.put("IsReturnPrintTemplate", electronicParam.getIsReturnPrintTemplate());
        json.put("Remark", electronicParam.getRemark());

        //发货人json
        JSONObject senderJson = new JSONObject();
        senderJson.put("Company", electronicParam.getSenderCompany());
        senderJson.put("Name", electronicParam.getSenderName());
        senderJson.put("Mobile", electronicParam.getSenderMobile());
        senderJson.put("ProvinceName", electronicParam.getSenderProvinceName());
        senderJson.put("CityName", electronicParam.getSenderCityName());
        senderJson.put("ExpAreaName", electronicParam.getSenderExpAreaName());
        senderJson.put("Address", electronicParam.getSenderAddress());
        json.put("Sender", senderJson);
        //收货人json
        JSONObject receiverJson = new JSONObject();
        receiverJson.put("Company", electronicParam.getReceiverCompany());
        receiverJson.put("Name", electronicParam.getReceiverName());
        receiverJson.put("Mobile", electronicParam.getReceiverMobile());
        receiverJson.put("ProvinceName", electronicParam.getReceiverProvinceName());
        receiverJson.put("CityName", electronicParam.getReceiverCityName());
        receiverJson.put("ExpAreaName", electronicParam.getReceiverExpAreaName());
        receiverJson.put("Address", electronicParam.getReceiverAddress());
        json.put("Receiver", receiverJson);
        //商品名称
        List<ElectronicCommodity> commodityList = electronicParam.getCommodityList();
        if (Objects.nonNull(commodityList) && !commodityList.isEmpty()){
            JSONArray jsonArray = new JSONArray();
            for (ElectronicCommodity commodity : commodityList) {
                JSONObject commodityJson = new JSONObject();
                commodityJson.put("GoodsName", commodity.getGoodsName());
                commodityJson.put("GoodsCode", commodity.getGoodsCode());
                commodityJson.put("Goodsquantity", commodity.getGoodsquantity());
                commodityJson.put("GoodsPrice", commodity.getGoodsPrice());
                commodityJson.put("GoodsWeight", commodity.getGoodsWeight());
                commodityJson.put("GoodsVol", commodity.getGoodsVol());
                jsonArray.add(commodityJson);
            }
            json.put("Commodity", jsonArray);
        }
        //增值服务
        List<ElectronicAddService> serviceList = electronicParam.getServiceList();
        if (Objects.nonNull(serviceList) && !serviceList.isEmpty()){
            JSONArray jsonArray = new JSONArray();
            for (ElectronicAddService service : serviceList) {
                JSONObject serviceJson = new JSONObject();
                serviceJson.put("Name", service.getName());
                serviceJson.put("Value", service.getValue());
                serviceJson.put("CustomerID", service.getCustomerID());
                jsonArray.add(serviceJson);
            }
            json.put("AddService", jsonArray);
        }
        log.info("电子面单请求参数====" + json.toString());

        // 组装系统级参数
        KdUtil kdUtil = new KdUtil();
        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", kdUtil.urlEncoder(json.toString(), "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1007");
        String dataSign=kdUtil.encrypt(json.toString(), ApiKey, "UTF-8");
        params.put("DataSign", kdUtil.urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");
        // 以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
        String result=kdUtil.sendPost(ReqURL, params);

        //根据公司业务处理返回的信息......
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        if ("100".equals(jsonObject.getString("ResultCode"))){
            //说明下单成功
            String printTemplate = jsonObject.getString("PrintTemplate");
            com.alibaba.fastjson.JSONObject reason = jsonObject.getJSONObject("Order");
            String LogisticCode = reason.getString("LogisticCode");

            Map<String, Object> map = new HashMap<>();
            map.put("logisticCode", LogisticCode);
            map.put("printTemplate", printTemplate);
            return R.ok(map);
        }else {
            return R.failed(jsonObject.getString("reason"));
        }
    }




}
